<template>
  <common-header />
  <div class="management-container">
    <n-card class="management-card">
      <template #header>
        <div class="card-title">
          <n-icon><BusinessOutline /></n-icon>
          场馆管理中心
        </div>
      </template>

      <n-tabs type="line" animated v-model:value="activeTab" class="management-tabs">
        <!-- 调试信息 -->
        <n-tab-pane name="debug" tab="调试信息" v-if="debugMode">
          <div class="debug-content">
            <n-card title="调试信息" size="small">
              <n-space vertical>
                <n-text>用户信息: {{ JSON.stringify(getUserInfo(), null, 2) }}</n-text>
                <n-text>场馆数据: {{ JSON.stringify(gymData, null, 2) }}</n-text>
                <n-text>gymData.id: {{ gymData.id }}</n-text>
                <n-text>判断条件(!gymData.id): {{ !gymData.id }}</n-text>
                <n-button @click="debugRefreshData">刷新数据</n-button>
                <n-button @click="debugMode = false">关闭调试</n-button>
              </n-space>
            </n-card>
          </div>
        </n-tab-pane>
        
        <!-- 场馆信息管理 -->        <n-tab-pane name="gym-info" tab="场馆信息">
          <div v-if="!gymData.id && !gymData.gymId" class="empty-state">
            <n-empty description="您还没有认领场馆">
              <template #extra>
                <n-alert type="info" style="margin-bottom: 16px;">
                  <template #header>
                    <n-icon><BusinessOutline /></n-icon>
                    场馆认领说明
                  </template>
                  要管理场馆，您需要先到场馆详情页面认领现有的POI场馆。认领成功后即可在此处管理场馆信息、时段设置等。
                </n-alert>
                <n-button type="primary" @click="goToGymView">
                  <template #icon>
                    <n-icon><LocationOutline /></n-icon>
                  </template>
                  去认领场馆
                </n-button>
              </template>
            </n-empty>
          </div>

          <div v-else class="gym-info-content">
            <!-- 场馆认领状态和来源信息 -->
            <n-alert 
              v-if="gymData.isPoiSource" 
              type="success" 
              style="margin-bottom: 20px;"
              :closable="false"
            >
              <template #header>
                <n-flex align="center" :size="8">
                  <n-icon><BusinessOutline /></n-icon>
                  <span>POI场馆认领成功</span>
                </n-flex>
              </template>
              <n-descriptions :column="2" size="small">
                <n-descriptions-item label="认领状态">
                  <n-tag :type="getStatusType(gymData.status)" size="small">
                    {{ getStatusText(gymData.status) }}
                  </n-tag>
                </n-descriptions-item>
                <n-descriptions-item label="认领时间" v-if="gymData.claimedAt">
                  {{ formatDate(gymData.claimedAt) }}
                </n-descriptions-item>
                <n-descriptions-item label="场馆来源">
                  <n-tag type="info" size="small">POI地图数据</n-tag>
                </n-descriptions-item>
                <n-descriptions-item label="POI ID" v-if="gymData.poiId">
                  <n-text depth="3" size="small">{{ gymData.poiId }}</n-text>
                </n-descriptions-item>
              </n-descriptions>
            </n-alert>
            
            <n-card :bordered="false" class="gym-card">
              <n-form
                ref="gymFormRef"
                :model="gymData"
                :rules="gymRules"
                label-placement="left"
                label-width="100"
                require-mark-placement="right-hanging"
                size="medium"
              >
                <n-grid :cols="2" :x-gap="12" responsive="screen">
                  <n-grid-item>
                    <n-form-item label="场馆名称" path="name">
                      <n-input v-model:value="gymData.name" placeholder="请输入场馆名称" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item label="场馆类型" path="type">
                      <n-select
                        v-model:value="gymData.type"
                        :options="gymTypeOptions"
                        placeholder="请选择场馆类型"
                      />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item span="2">
                    <n-form-item label="详细地址" path="address">
                      <n-input v-model:value="gymData.address" placeholder="请输入详细地址" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item label="联系电话" path="phone">
                      <n-input v-model:value="gymData.phone" placeholder="请输入联系电话" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item>
                    <n-form-item label="营业时间" path="opening_hours">
                      <n-input v-model:value="gymData.opening_hours" placeholder="例如：08:00-22:00" />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item span="2">
                    <n-form-item label="场馆描述" path="description">
                      <n-input
                        v-model:value="gymData.description"
                        type="textarea"
                        placeholder="请输入场馆描述"
                        :autosize="{ minRows: 3, maxRows: 5 }"
                      />
                    </n-form-item>
                  </n-grid-item>                  <n-grid-item span="2">
                    <n-form-item label="设施器械">
                      <n-dynamic-tags
                        v-model:value="gymData.facilities"
                        :max="20"
                        @create="handleCreateFacility"
                      />
                    </n-form-item>
                  </n-grid-item>                </n-grid>
                  <!-- 营业状态管理 -->
                <n-divider />
                <n-form-item label="营业状态">
                  <n-flex align="center" :size="12">
                    <n-tag :type="getStatusType(gymData.status)" size="medium">
                      {{ getStatusText(gymData.status) }}
                    </n-tag>
                    <n-select
                      v-if="gymData.status !== 'unclaimed'"
                      v-model:value="gymData.status"
                      :options="statusOptions"
                      style="width: 120px;"
                      @update:value="handleChangeStatus"
                      :loading="changingStatus"
                      size="small"
                    />
                    <n-text v-else depth="3" size="small">
                      场馆未认领，无法修改状态
                    </n-text>
                  </n-flex>
                  <n-text depth="3" size="small" style="margin-top: 8px; display: block;">
                    {{ getStatusDescription(gymData.status) }}
                  </n-text>
                </n-form-item>
                
                <!-- 操作按钮 -->
                <n-flex justify="end" style="margin-top: 20px;" :size="12">
                  <n-button @click="handleResetGym" :disabled="saving">重置</n-button>
                  <n-button type="primary" @click="handleSaveGym" :loading="saving">保存修改</n-button>
                </n-flex>
              </n-form>
            </n-card>
          </div>
        </n-tab-pane>        <!-- 时段管理 -->
        <n-tab-pane name="time-slots" tab="时段管理" :disabled="!gymData.id && !gymData.gymId">
          <div class="time-slots-content">
            <div class="time-slots-header">
              <n-text strong>可预约时段设置</n-text>
              <n-button type="primary" @click="showAddTimeSlotModal = true">
                <template #icon>
                  <n-icon><Add /></n-icon>
                </template>
                添加时段
              </n-button>
            </div>

            <n-tabs type="card" v-model:value="selectedDay" class="week-tabs">
              <n-tab-pane 
                v-for="day in weekDays" 
                :key="day.value" 
                :name="day.value" 
                :tab="day.label"
              >
                <div class="day-time-slots">
                  <div v-if="!getTimeSlotsForDay(day.value).length" class="empty-slots">
                    <n-empty description="暂无时段设置" size="small">
                      <template #extra>
                        <n-button size="small" @click="addTimeSlotForDay(day.value)">
                          添加时段
                        </n-button>
                      </template>
                    </n-empty>
                  </div>
                  
                  <div v-else class="slots-list">
                    <n-card 
                      v-for="slot in getTimeSlotsForDay(day.value)" 
                      :key="slot.id" 
                      size="small" 
                      class="slot-card"
                    >
                      <n-flex justify="space-between" align="center">
                        <n-space>
                          <n-tag :bordered="false" type="info">
                            {{ slot.start_time }} - {{ slot.end_time }}
                          </n-tag>
                          <n-text>{{ slot.price }}元</n-text>
                          <n-text depth="3">容量: {{ slot.max_capacity }}人</n-text>
                        </n-space>
                        <n-space>
                          <n-switch 
                            v-model:value="slot.is_active" 
                            @update:value="handleToggleSlot(slot)"
                          />
                          <n-button size="tiny" @click="editTimeSlot(slot)">编辑</n-button>
                          <n-button size="tiny" type="error" @click="deleteTimeSlot(slot)">删除</n-button>
                        </n-space>
                      </n-flex>
                    </n-card>
                  </div>
                </div>
              </n-tab-pane>
            </n-tabs>
          </div>
        </n-tab-pane>        <!-- 预约管理 -->
        <n-tab-pane name="reservations" tab="预约管理" :disabled="!gymData.id && !gymData.gymId">
          <div class="reservations-content">
            <div class="reservations-header">
              <n-space align="center">
                <n-text strong>预约记录</n-text>
                <n-select
                  v-model:value="reservationFilter"
                  :options="reservationFilterOptions"
                  style="width: 120px;"
                  @update:value="fetchReservations"
                />
                <n-date-picker
                  v-model:value="selectedDate"
                  type="date"
                  placeholder="选择日期"
                  @update:value="fetchReservations"
                />
              </n-space>
            </div>

            <n-data-table
              :columns="reservationColumns"
              :data="reservations"
              :loading="loadingReservations"
              :pagination="reservationPagination"
              remote
              @update:page="handleReservationPageChange"
            />
          </div>
        </n-tab-pane>
      </n-tabs>
    </n-card>

    <!-- 添加时段弹窗 -->
    <n-modal v-model:show="showAddTimeSlotModal" preset="dialog" title="添加时段">
      <n-form
        ref="timeSlotFormRef"
        :model="newTimeSlot"
        :rules="timeSlotRules"
        label-placement="left"
        label-width="100"
      >
        <n-form-item label="星期" path="day_of_week">
          <n-select
            v-model:value="newTimeSlot.day_of_week"
            :options="weekDays"
            placeholder="请选择星期"
          />
        </n-form-item>
        <n-form-item label="开始时间" path="start_time">
          <n-time-picker v-model:value="newTimeSlot.start_time" format="HH:mm" />
        </n-form-item>
        <n-form-item label="结束时间" path="end_time">
          <n-time-picker v-model:value="newTimeSlot.end_time" format="HH:mm" />
        </n-form-item>
        <n-form-item label="价格" path="price">
          <n-input-number v-model:value="newTimeSlot.price" :min="0" :precision="2">
            <template #suffix>元</template>
          </n-input-number>
        </n-form-item>
        <n-form-item label="最大容量" path="max_capacity">
          <n-input-number v-model:value="newTimeSlot.max_capacity" :min="1" :precision="0">
            <template #suffix>人</template>
          </n-input-number>
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="showAddTimeSlotModal = false">取消</n-button>
          <n-button type="primary" @click="handleAddTimeSlot" :loading="addingTimeSlot">添加</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, h } from 'vue'
import { useMessage, NTag, NButton, NSpace } from 'naive-ui'
import { BusinessOutline, Add, LocationOutline } from '@vicons/ionicons5'
import { useRouter } from 'vue-router'
import CommonHeader from '../../components/CommonHeader.vue'
import http from '../../utils/http.js'
import qs from 'qs'

const message = useMessage()
const router = useRouter()
const BASE_URL = window.BASE_URL

// 响应式数据
const activeTab = ref('gym-info')
const selectedDay = ref(1)
const selectedDate = ref(null)
const reservationFilter = ref('all')
const debugMode = ref(true) // 启用调试模式

// 加载状态
const saving = ref(false)
const addingTimeSlot = ref(false)
const loadingReservations = ref(false)

// 弹窗状态
const showAddTimeSlotModal = ref(false)

// 表单引用
const gymFormRef = ref(null)
const timeSlotFormRef = ref(null)

// 场馆数据
const gymData = ref({
  id: null,
  gymId: null,
  userId: null,
  name: '',
  type: '',
  address: '',
  phone: '',
  description: '',
  opening_hours: '',
  facilities: [],
  status: 'unclaimed',
  images: '',
  photos: [], // POI照片数组
  rating: null, // POI评分
  tel: '', // POI电话字段
  adname: '', // POI区域名称
  distance: null, // POI距离
  claimedAt: null, // 认领时间
  claimedStaff: null, // 认领员工信息
  isPoiSource: false, // 是否来自POI数据源
  poiId: null // POI ID
})

// 状态变量
const changingStatus = ref(false)

// 时段数据
const timeSlots = ref([])
const newTimeSlot = ref({
  day_of_week: null,
  start_time: null,
  end_time: null,
  price: null,
  max_capacity: 1
})

// 预约数据
const reservations = ref([])
const reservationPagination = ref({
  page: 1,
  pageSize: 10,
  itemCount: 0
})

// 选项
const gymTypeOptions = [
  { label: '健身房', value: '健身房' },
  { label: '瑜伽馆', value: '瑜伽馆' },
  { label: '游泳馆', value: '游泳馆' },
  { label: '拳击馆', value: '拳击馆' },
  { label: '羽毛球馆', value: '羽毛球馆' },
  { label: '乒乓球馆', value: '乒乓球馆' },
  { label: '篮球馆', value: '篮球馆' },
  { label: '网球馆', value: '网球馆' },
  { label: '台球厅', value: '台球厅' },
  { label: '保龄球馆', value: '保龄球馆' },
  { label: '跆拳道馆', value: '跆拳道馆' },  { label: '舞蹈室', value: '舞蹈室' }
]

const statusOptions = [
  { label: '营业中', value: 'active' },
  { label: '暂停营业', value: 'inactive' }
]

const weekDays = [
  { label: '周一', value: 1 },
  { label: '周二', value: 2 },
  { label: '周三', value: 3 },
  { label: '周四', value: 4 },
  { label: '周五', value: 5 },
  { label: '周六', value: 6 },
  { label: '周日', value: 7 }
]

const reservationFilterOptions = [
  { label: '全部', value: 'all' },
  { label: '待确认', value: 'pending' },
  { label: '已确认', value: 'confirmed' },
  { label: '已取消', value: 'cancelled' },
  { label: '已完成', value: 'completed' }
]

// 表单验证规则
const gymRules = {
  name: { required: true, message: '请输入场馆名称', trigger: 'blur' },
  type: { required: true, message: '请选择场馆类型', trigger: 'change' },
  address: { required: true, message: '请输入详细地址', trigger: 'blur' },
  phone: { 
    required: true,
    trigger: 'blur',
    pattern: /^1[3-9]\d{9}$/,
    message: '请输入正确的手机号格式'
  }
}

const timeSlotRules = {
  day_of_week: { required: true, message: '请选择星期', trigger: 'change' },
  start_time: { required: true, message: '请选择开始时间', trigger: 'change' },
  end_time: { required: true, message: '请选择结束时间', trigger: 'change' },
  price: { required: true, message: '请输入价格', trigger: 'blur' },
  max_capacity: { required: true, message: '请输入最大容量', trigger: 'blur' }
}

// 预约表格列
const reservationColumns = [
  { title: '预约日期', key: 'reservation_date', width: 120 },
  { title: '时间段', key: 'time_slot', width: 150, render: (row) => `${row.start_time} - ${row.end_time}` },
  { title: '用户', key: 'user_name', width: 100 },
  { title: '联系电话', key: 'user_phone', width: 120 },
  { title: '价格', key: 'price', width: 80, render: (row) => `¥${row.price}` },
  { 
    title: '状态', 
    key: 'status', 
    width: 100,
    render: (row) => {
      const statusMap = {
        pending: { type: 'warning', text: '待确认' },
        confirmed: { type: 'success', text: '已确认' },
        cancelled: { type: 'error', text: '已取消' },
        completed: { type: 'info', text: '已完成' }
      }
      const status = statusMap[row.status] || { type: 'default', text: row.status }
      return h(NTag, { type: status.type }, { default: () => status.text })
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    render: (row) => {
      return h(NSpace, {}, {
        default: () => [
          row.status === 'pending' ? h(NButton, { 
            size: 'small', 
            type: 'success',
            onClick: () => handleConfirmReservation(row)
          }, { default: () => '确认' }) : null,
          row.status === 'pending' ? h(NButton, { 
            size: 'small', 
            type: 'error',
            onClick: () => handleCancelReservation(row)
          }, { default: () => '取消' }) : null
        ].filter(Boolean)
      })
    }
  }
]

// 计算属性
const getTimeSlotsForDay = (day) => {
  return timeSlots.value.filter(slot => slot.day_of_week === day)
}

// 获取用户信息
const getUserInfo = () => {
  return localStorage.user ? JSON.parse(localStorage.user) : null
}

// 方法
const handleCreateFacility = (label) => {
  return {
    label,
    value: label
  }
}

const addTimeSlotForDay = (day) => {
  newTimeSlot.value.day_of_week = day
  showAddTimeSlotModal.value = true
}


// 获取场馆信息
const fetchGymData = async () => {
  try {
    const userInfo = getUserInfo()
    if (!userInfo) {
      console.log('用户信息不存在')
      return
    }    console.log('正在获取用户认领的场馆信息, userId:', userInfo.userId)
    const response = await http.get(`/v1/gym/owner/${userInfo.userId}`)
    console.log('API响应:', response.data)
      if (response.data.code === 2000 && response.data.data) {
      const data = response.data.data
      
      // 将后端状态值映射到前端状态值
      let frontendStatus = data.status
      if (data.status === 'open') {
        frontendStatus = 'active'
      } else if (data.status === 'closed') {
        frontendStatus = 'inactive'
      }
      
      gymData.value = {
        ...data,
        id: data.gymId, // 映射gymId到id字段，用于前端显示判断
        status: frontendStatus, // 使用映射后的状态
        facilities: data.facilities ? JSON.parse(data.facilities) : []
      }
      console.log('获取场馆信息成功:', gymData.value)
    } else {
      console.log('未找到认领的场馆信息, 响应码:', response.data.code, '消息:', response.data.msg)
      // 重置场馆数据
      gymData.value = {
        id: null,
        gymId: null,
        userId: null,
        name: '',
        type: '',
        address: '',
        phone: '',
        description: '',
        opening_hours: '',
        facilities: [],
        status: 'unclaimed',
        images: '',
        photos: [],
        rating: null,
        tel: '',
        adname: '',
        distance: null,
        claimedAt: null,
        claimedStaff: null,
        isPoiSource: false,
        poiId: null
      }
    }
  } catch (error) {
    console.error('获取场馆信息失败:', error)
    // 检查是否是权限错误
    if (error.response && error.response.status === 401) {
      message.error('登录已过期，请重新登录')
      router.push('/login')
    } else {
      message.error('获取场馆信息失败，请稍后重试')
    }
  }
}

// 获取时段信息
const fetchTimeSlots = async () => {
  try {
    const gymId = gymData.value.id || gymData.value.gymId
    if (!gymId) return

    const response = await http.get(`/v1/gym/${gymId}/time-slots`)
    if (response.data.code === 2000) {
      timeSlots.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取时段信息失败:', error)
  }
}

// 获取预约信息
const fetchReservations = async () => {
  try {
    const gymId = gymData.value.id || gymData.value.gymId
    if (!gymId) return

    loadingReservations.value = true
    const params = {
      gymId: gymId,
      page: reservationPagination.value.page,
      pageSize: reservationPagination.value.pageSize,
      status: reservationFilter.value === 'all' ? null : reservationFilter.value,
      date: selectedDate.value ? new Date(selectedDate.value).toISOString().split('T')[0] : null
    }

    const response = await http.get(`/v1/gym/reservations`, { params })
    if (response.data.code === 2000) {
      reservations.value = response.data.data.records || []
      reservationPagination.value.itemCount = response.data.data.total || 0
    }
  } catch (error) {
    console.error('获取预约信息失败:', error)
  } finally {
    loadingReservations.value = false
  }
}



// 保存场馆信息
const handleSaveGym = async () => {
  gymFormRef.value?.validate(async (errors) => {
    if (!errors) {
      saving.value = true
      try {
        // TODO: 实现场馆信息更新API
        message.info('保存功能开发中，暂时不可用')
        
        /* 
        const submitData = {
          ...gymData.value,
          facilities: JSON.stringify(gymData.value.facilities)
        }

        const response = await http.post(`/v1/gym/update`, qs.stringify(submitData))
        if (response.data.code === 2000) {
          message.success('保存成功')
          await fetchGymData()
        } else {
          message.error(response.data.msg || '保存失败')
        }
        */
      } catch (error) {
        console.error('保存场馆信息失败:', error)
        message.error('保存失败，请稍后重试')
      } finally {
        saving.value = false
      }
    }
  })
}

// 重置场馆信息
const handleResetGym = () => {
  fetchGymData()
}

// 更改营业状态
const handleChangeStatus = async (newStatus) => {
  try {
    changingStatus.value = true
    
    // 将前端状态值映射到后端期望的值
    const backendStatus = newStatus === 'active' ? 'open' : 'closed'
    
    const response = await http.put(`/v1/gym/${gymData.value.gymId}/status`, {
      status: backendStatus
    })
    
    if (response.data.code === 2000) {
      gymData.value.status = newStatus
      message.success(`场馆状态已更新为: ${getStatusText(newStatus)}`)
    } else {
      message.error(response.data.msg || '状态更新失败')
    }
  } catch (error) {
    console.error('状态更新失败:', error)
    message.error('状态更新失败，请稍后重试')
  } finally {
    changingStatus.value = false
  }
}

// 添加时段
const handleAddTimeSlot = async () => {
  timeSlotFormRef.value?.validate(async (errors) => {
    if (!errors) {
      addingTimeSlot.value = true
      try {
        const gymId = gymData.value.id || gymData.value.gymId
        const timeSlotData = {
          gym_id: gymId,
          day_of_week: newTimeSlot.value.day_of_week,
          start_time: new Date(newTimeSlot.value.start_time).toTimeString().slice(0, 8),
          end_time: new Date(newTimeSlot.value.end_time).toTimeString().slice(0, 8),
          price: newTimeSlot.value.price,
          max_capacity: newTimeSlot.value.max_capacity
        }

        const response = await http.post(`/v1/gym/time-slots/create`, qs.stringify(timeSlotData))
        if (response.data.code === 2000) {
          message.success('时段添加成功')
          showAddTimeSlotModal.value = false
          await fetchTimeSlots()
          // 重置表单
          newTimeSlot.value = {
            day_of_week: null,
            start_time: null,
            end_time: null,
            price: null,
            max_capacity: 1
          }
        } else {
          message.error(response.data.msg || '添加失败')
        }
      } catch (error) {
        console.error('添加时段失败:', error)
        message.error('添加失败，请稍后重试')
      } finally {
        addingTimeSlot.value = false
      }
    }
  })
}

// 切换时段状态
const handleToggleSlot = async (slot) => {
  try {
    const response = await http.post(`/v1/gym/time-slots/toggle`, qs.stringify({
      id: slot.id,
      is_active: slot.is_active
    }))
    if (response.data.code === 2000) {
      message.success(slot.is_active ? '时段已启用' : '时段已禁用')
    } else {
      message.error(response.data.msg || '操作失败')
      slot.is_active = !slot.is_active // 回滚
    }
  } catch (error) {
    console.error('切换时段状态失败:', error)
    message.error('操作失败，请稍后重试')
    slot.is_active = !slot.is_active // 回滚
  }
}

// 编辑时段
const editTimeSlot = (slot) => {
  // TODO: 实现编辑时段功能
  message.info('编辑功能开发中...')
}

// 删除时段
const deleteTimeSlot = async (slot) => {
  try {
    const response = await http.delete(`/v1/gym/time-slots/${slot.id}`)
    if (response.data.code === 2000) {
      message.success('时段删除成功')
      await fetchTimeSlots()
    } else {
      message.error(response.data.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除时段失败:', error)
    message.error('删除失败，请稍后重试')
  }
}

// 确认预约
const handleConfirmReservation = async (reservation) => {
  try {
    const response = await http.post(`/v1/gym/reservations/confirm`, qs.stringify({
      id: reservation.id
    }))
    if (response.data.code === 2000) {
      message.success('预约已确认')
      await fetchReservations()
    } else {
      message.error(response.data.msg || '确认失败')
    }
  } catch (error) {
    console.error('确认预约失败:', error)
    message.error('确认失败，请稍后重试')
  }
}

// 取消预约
const handleCancelReservation = async (reservation) => {
  try {
    const response = await http.post(`/v1/gym/reservations/cancel`, qs.stringify({
      id: reservation.id
    }))
    if (response.data.code === 2000) {
      message.success('预约已取消')
      await fetchReservations()
    } else {
      message.error(response.data.msg || '取消失败')
    }
  } catch (error) {
    console.error('取消预约失败:', error)
    message.error('取消失败，请稍后重试')
  }
}

// 分页处理
const handleReservationPageChange = (page) => {
  reservationPagination.value.page = page
  fetchReservations()
}

// 跳转到场馆认领页面
const goToGymView = () => {
  router.push('/gym')
}

// 调试方法
const debugRefreshData = async () => {
  console.log('=== 开始调试刷新数据 ===')
  await fetchGymData()
  console.log('=== 调试刷新数据完成 ===')
}

// 状态格式化方法
const getStatusType = (status) => {
  switch (status) {
    case 'active':
      return 'success'
    case 'inactive': 
      return 'warning'
    case 'unclaimed':
      return 'info'
    default:
      return 'default'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 'active':
      return '营业中'
    case 'inactive':
      return '暂停营业'
    case 'unclaimed':
      return '未认领'
    default:
      return '未知状态'
  }
}

const getStatusDescription = (status) => {
  switch (status) {
    case 'active':
      return '场馆正常营业中，用户可以预约时段'
    case 'inactive':
      return '场馆当前暂停营业，暂时无法接受预约'
    case 'unclaimed':
      return '场馆尚未认领，需要先认领才能管理'
    default:
      return '状态未知'
  }
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

// 页面加载时执行
onMounted(async () => {
  await fetchGymData()
  const gymId = gymData.value.id || gymData.value.gymId
  if (gymId) {
    // TODO: 实现时段管理API后启用
    // await fetchTimeSlots()
    // await fetchReservations()
    console.log('场馆信息加载完成，时段和预约功能待实现')
  }
})
</script>

<style scoped>
.management-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.management-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.management-tabs {
  margin-top: 20px;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.gym-info-content {
  padding: 20px 0;
}

.gym-card {
  background: #fafafa;
}

.time-slots-content {
  padding: 20px 0;
}

.time-slots-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.week-tabs {
  margin-top: 16px;
}

.day-time-slots {
  min-height: 200px;
}

.empty-slots {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 150px;
}

.slots-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.slot-card {
  border: 1px solid #e8e8e8;
  transition: all 0.3s ease;
}

.slot-card:hover {
  border-color: #2080f0;
  box-shadow: 0 2px 8px rgba(32, 128, 240, 0.1);
}

.reservations-content {
  padding: 20px 0;
}

.reservations-header {
  margin-bottom: 20px;
}

:deep(.n-dynamic-tags .n-tag) {
  margin: 4px;
}

:deep(.n-form-item-label) {
  font-weight: 500;
}
</style>
